<template>
  <div id="app">
    <div :id="id" ref="videoRef" style="width: 100%; height: 100%" @dblclick="fullscreen"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, nextTick, reactive } from 'vue';
import { liveAddr } from '@/api/video';

// 声明全局类型
declare const SdsesPlayer: any;

const props = defineProps({
  id: {
    type: String,
    default: '#videoBox'
  },
  cameraIndexCode: {
    type: String
  }
});
const videoRef = ref(null);
let player = reactive<any>(null);
const params = ref({
  cameraIndexCode: '1036-100001941000',
  protocol: 'sstp-over-websocket',
  streamType: '1'
});

// 初始化播放器
const initPlayer = async () => {
  await nextTick();
  const container = videoRef.value;
  console.log('container', container);
  if (!container) {
    console.error(`容器元素 ${props.id} 未找到`);
    return;
  }

  // 确保清理旧实例
  if (player) {
    try {
      if (typeof player.stop === 'function') {
        player.stop();
      }
      if (typeof player.destroy === 'function') {
        player.destroy();
      }
    } catch (error) {
      console.warn('清理旧播放器实例时出错:', error);
    } finally {
      player = null;
    }
  }

  try {
    player = new SdsesPlayer({
      container: container,
      lang: 'zh',
      autoplay: true,
      controls: true
    });
  } catch (error) {
    console.error('创建SdsesPlayer实例失败:', error);
  }
};

// 播放视频
const playVideo = async () => {
  try {
    if (!player) {
      await initPlayer();
    }
    if (!player) {
      console.error('播放器初始化失败');
      return;
    }
    params.value.cameraIndexCode = props.cameraIndexCode;
    const res = await liveAddr(params.value);
    if (res && res.data && res.data.addr && player && typeof player.play === 'function') {
      player.play(res.data.addr, 'preview', {
        stream: res.data.addr.replace(/^wss?/, 'sstp')
      });
    }
  } catch (error) {
    console.error('播放视频失败:', error);
  }
};

// 监听 cameraIndexCode 的变化
watch(
  () => props.cameraIndexCode,
  (val) => {
    params.value.cameraIndexCode = val;
    playVideo();
  },
  { immediate: true }
);

// 全屏
const fullscreen = () => {
  if (player) {
    player.fullscreen();
  }
};

// 组件挂载时初始化播放器
onMounted(async () => {
  await nextTick();
  await playVideo();
});

// 组件卸载时清理播放器
onUnmounted(() => {
  if (player) {
    try {
      // 先停止播放器，确保所有worker都正确停止
      if (typeof player.stop === 'function') {
        player.stop();
      }
      // 延迟销毁，确保worker有足够时间清理
      setTimeout(() => {
        try {
          if (player && typeof player.destroy === 'function') {
            player.destroy();
          }
        } catch (error) {
          console.warn('VideoPlayer销毁时出错:', error);
        } finally {
          player = null;
        }
      }, 100);
    } catch (error) {
      console.warn('VideoPlayer停止时出错:', error);
      player = null;
    }
  }
});
</script>

<style scoped>
/* 这里可以添加样式 */
</style>
